package com.zy.batiya.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.zy.batiya.domain.InventoryItem;
import com.zy.batiya.domain.Pager;
import com.zy.batiya.domain.Room;
import com.zy.batiya.dto.InventoryItemDTO;
import com.zy.batiya.mapper.InventoryItemMapper;
import com.zy.batiya.mapper.RoomMapper;
import com.zy.batiya.service.InventoryItemService;
import com.zy.batiya.util.CommonUtils;
import com.zy.batiya.util.DateUtil;

@Transactional
@Component
public class InventoryItemServiceImpl implements InventoryItemService{
  
  @Autowired
  private InventoryItemMapper inventoryItemMapper;
  
  @Autowired
  private RoomMapper roomMapper;
  
  @Override
  public void insert(InventoryItem obj) {
    inventoryItemMapper.insert(obj);
  }

  @Override
  public List<Map<String, String>> searchInventory(Map<String, String> map) {   
    return inventoryItemMapper.searchInventory(map);
  }

  @Override
  public void update(InventoryItem obj) {
    inventoryItemMapper.update(obj);
  }

  @Override
  public InventoryItem findById(int id) {
    return inventoryItemMapper.findById(id);
  }

  @Override
  public void init(String pid, String uid, String begin, String end) {
    try {
      List<Room> rooms = roomMapper.search(pid, uid, null);
      for(Room room:rooms){
        List<String> dts = DateUtil.getDtList(begin, end, "yyyy-MM-dd");
        for(String dt:dts){
          InventoryItem item = new InventoryItem();
          item.setDt(dt);
          item.setIsOrdered(0);
          item.setPartner_pid(pid);
          item.setPartner_uid(uid);
          item.setRoomId(room.getId());
          item.setRoomNumber(room.getNumber());
          
          inventoryItemMapper.insert(item);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  @Override
  public Pager<List<InventoryItem>> list(Pager<InventoryItemDTO> pager) throws Exception {
    Pager<List<InventoryItem>> result = new Pager<List<InventoryItem>>();
    try{
        InventoryItemDTO obj = pager.getT();
        Integer total = inventoryItemMapper.countList(obj);
        Integer totalpage = CommonUtils.getTotalPage(pager, total);
        Integer begin = (pager.getPagenow() - 1) * pager.getSize();
        obj.setStart(begin);
        obj.setSize(pager.getSize());
        obj.setOrder(pager.getOrder());
        obj.setOrderCol(pager.getOrderCol());
        List<InventoryItem> list = inventoryItemMapper.list(obj);
        result.setTotal(total);
        result.setT(list);
        result.setTotalpage(totalpage);
    }catch(Exception e){
        e.printStackTrace();
        throw new Exception("BillServiceImp.class findByCase function error : " + e.toString());
    }
    return result;
  }

}
